package com.gitee.faster.webdav.kernel.resource.local;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.net.URLEncodeUtil;
import cn.hutool.core.util.StrUtil;
import com.gitee.faster.webdav.kernel.Configuration;
import com.gitee.faster.webdav.kernel.resource.Resource;
import com.gitee.faster.webdav.kernel.model.Owner;
import lombok.Getter;

import java.io.File;
import java.util.Date;
import java.util.Objects;

/**
 * 本地资源
 * 文件或目录都被视为一种资源
 *
 * @author hongda.li
 */
@Getter
public class LocalResource implements Resource {
    /**
     * 归属者
     */
    private static final Owner LOCAL_OWNER = Owner.byName("Local");

    /**
     * 本地文件映射
     */
    private final File file;

    /**
     * 是否为根目录
     */
    private final boolean root;

    /**
     * 本地存储根目录，后缀不包含 /
     */
    private final String rootPath;

    public LocalResource(File file) {
        this.file = file;
        this.rootPath = Configuration.getInstance().withReplacedStoragePath();
        this.root = Objects.equals(this.rootPath, this.file.getAbsolutePath());
    }

    public LocalResource(String requestPath) {
        this.rootPath = Configuration.getInstance().withReplacedStoragePath();
        this.file = new File(this.rootPath, requestPath);
        this.root = Objects.equals(this.rootPath, this.file.getAbsolutePath());
    }

    @Override
    public boolean isRoot() {
        return this.root;
    }

    @Override
    public Owner getOwner() {
        return LOCAL_OWNER;
    }

    @Override
    public boolean exists() {
        return FileUtil.exist(this.file);
    }

    @Override
    public boolean isFile() {
        return FileUtil.isFile(this.file);
    }

    @Override
    public boolean isDirectory() {
        return FileUtil.isDirectory(this.file);
    }

    @Override
    public String getName() {
        return FileUtil.getName(this.file);
    }

    @Override
    public Date lastModified() {
        return FileUtil.lastModifiedTime(this.file);
    }

    @Override
    public long length() {
        return isFile() ? this.file.length() : 0L;
    }

    @Override
    public String requestPath() {
        // 绝对路径
        String absolutePath = this.file.getAbsolutePath();
        // 相对路径
        String path = StrUtil.removePrefix(absolutePath, this.rootPath).replace(StrUtil.BACKSLASH, StrUtil.SLASH);
        // 引用路径
        return URLEncodeUtil.encode(this.file.isFile()
                ? path
                : StrUtil.addSuffixIfNot(path, StrUtil.SLASH));
    }
}